package com.gt.web.srv.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.web.srv.domain.SysConfig;
import com.gt.web.srv.mapper.SysConfigMapper;
import com.gt.web.srv.service.ISysConfigService;
import com.gt.web.srv.utils.BizUtils;
import com.gt.web.srv.utils.GtConstants;
import com.gt.web.srv.utils.RedisClient;
import com.gt.web.srv.web.api.resource.dto.ScoreConfigDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author family
* @description 针对表【sys_config(参数配置表)】的数据库操作Service实现
* @createDate 2024-07-10 11:20:16
*/
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

	@Resource
	private RedisClient redisClient;

	/**
	 * 获取积分配置
	 *
	 * @return
	 */
	@Override
	public ScoreConfigDto getScoreConfig() {

		Long[] ids = {7l,8l,9l};
		LambdaQueryWrapper<SysConfig> lambda = new LambdaQueryWrapper<>();
		lambda.in(SysConfig::getConfigId,ids);
		List<SysConfig> sysConfigs = this.baseMapper.selectList(lambda);
		ScoreConfigDto dto = new ScoreConfigDto();
		for (SysConfig sysConfig : sysConfigs) {
			if(sysConfig.getConfigId().equals(7l)){
				String[] s = sysConfig.getConfigValue().split("_");
				dto.setStart(BizUtils.str2Time(s[0]));
				dto.setEnd(BizUtils.str2Time(s[1]));
			}
			else if (sysConfig.getConfigId().equals(8l)) {
				dto.setLoginScore(sysConfig.getConfigValue());
			}
			else if (sysConfig.getConfigId().equals(9l)) {
				dto.setRewardScore(sysConfig.getConfigValue());
			}
			else {}
		}
		return dto;
	}

	@Override
	public String selectConfigByKey(String configKey) {
		String configValue = redisClient.getString(getCacheKey(configKey));
		if (StrUtil.isNotBlank(configValue)) {
			return configValue;
		}
		LambdaUpdateWrapper<SysConfig> queryWrapper = new LambdaUpdateWrapper<>();
		queryWrapper.eq(SysConfig::getConfigKey, configKey);
		queryWrapper.last(" limit 1 ");
		SysConfig retConfig = this.baseMapper.selectOne(queryWrapper);
		if (ObjectUtil.isNotNull(retConfig)) {
			redisClient.set(getCacheKey(configKey), retConfig.getConfigValue());
			return retConfig.getConfigValue();
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 设置cache key
	 *
	 * @param configKey 参数键
	 * @return 缓存键key
	 */
	private String getCacheKey(String configKey) {
		return GtConstants.SYS_CONFIG_KEY + configKey;
	}

}




